<?php
/**
 * 网站操作类
 * Created		: 2009-12-18
 * Modified		: 2010-10-25
 * @version	: 0.1.0
 * @author		: Joseph Chen (jsph.chen@gmail.com)
 */
class Site
{

	/**
	 * 表名
	 * @var string
	 */
	const TBL	= 'site';

	/**
	 * 站点类别表名
	 * @var string
	 */
	const TBL_CATEGORY	= 'site_category';
	
	/**
	 * 每页显示几条记录
	 * @var int
	 */
	public static $pageSize = 30;
	
	/**
	 * 分页条代码
	 * @var string
	 */
	public static $pagePanel = '';
	
	
	/**
	 * 根据主键ID读取一条记录
	 * @param int $id
	 */
	public static function read($id) 
	{
		return Db::read($GLOBALS['tbl_pre'].self::TBL, (int)$id);
	}
	
	/**
	 * 获取列表
	 * @param int $cid
	 * @param int $pageSize
	 * @param boolean $hasPages
	 */
	public static function getList($cid=null, $pageSize=30, $hasPages=true) 
	{
		empty($pageSize) && $pageSize = self::$pageSize;
		
		$_whr = array();
		$params = array();
		
		if ($cid) {
			$_whr[] = 'cid='.$cid;
		}
		
		if (!empty($_GET['keyword']))
		{
			$_whr[] = 'title like :title';
			$params['title'] = '%'.$kw.'%';
		}
		
		//关键字查询
		if ($_whr)
		{
			$where = join(' and ', $_whr);
		} else {
			$where = '';
		}
		$rows = Db::getCounts($GLOBALS['tbl_pre'].self::TBL, $where, $params);
		if (!$rows && !is_null(Db::errors())) {
			App::msg(Db::$errors[2]);
			return false;
		}
		if ($hasPages)
		{
			Page::init($pageSize, $rows);
			Page::setFromTo($pageSize);
			$pageStart = Page::$from;
		} else {
			$hasPages = false;
			$pageStart = 0;
		}
		$list = Db::select(
	 					$GLOBALS['tbl_pre'].self::TBL, 
	 					$where, 
	 					'*', 
	 					$params, 
	 					'', 
	 					$pageStart, 
	 					$pageSize
		);
		//如果列表有分页,则进行分页操作
		if ($hasPages == 1)
		{
			self::$pagePanel = Page::generate($_POST);
		}
		return $list;
	}
	
	/**
	 * 更新站点代码
	 * @param array $site
	 */
	public static function updateCode($data) 
	{
		extract($data);
		
		// 对应数据库是否已经存在
		$db = Db::init(
			array(
				'host' => $db_host,
				'name' => $db_name,
				'user' => $db_user,
				'pass' => $db_pass,
				'charset' => $db_charset,
			),
			$db_name
		);
		if (!$db) {
			$sqlFile = APP_ROOT.'Config/sql/base.sql';
			$sql = file_get_contents($sqlFile);
			$replacement = array(
				'{db_name}'	=> $db_name, 
				'{tbl_pre}'	=> $tbl_pre,
				'{lang}'	=> $default_lang,
			);
			$sql = strtr($sql, $replacement);
			Db::execute($sql);
			
			if (in_array('faq', $module_list)) {
				foreach ($lang as $l) {
					$langFile = APP_ROOT . 'Lang/' . $l . DS . 'common.lang.php';
					$arr = include $langFile;
					$data = array(
						'name'	=> $arr['FaqText'],
						'lang'	=> $l
					);
					Db::insert($tbl_pre.'news_category', $data);
				}
			}
		}
		
		$siteDir = SITE_LIST.$sign.DS;
		if ($siteDir) {
			Fso::rmdir($siteDir);
		}
		Fso::mkdir($siteDir);
		Fso::mkdir($siteDir.'App/');
		Fso::mkdir($siteDir.'App/Base');
		Fso::mkdir($siteDir.'App/Config');
		Fso::mkdir($siteDir.'App/Data');
		Fso::mkdir($siteDir.'App/Lang');
		Fso::mkdir($siteDir.'App/Mo');
		Fso::mkdir($siteDir.'App/Util');
		Fso::mkdir($siteDir.'App/View');
		Fso::mkdir($siteDir.'Webroot');
		copy(APP_ROOT.'global.php', $siteDir.'App/global.php');
		
		// 复制管理后台代码
		global $app_admin;
		$siteAdminDir = $siteDir.'App/Admin/';
		$siteAdminActionDir = $siteDir.'App/Admin/action/';
		Fso::mkdir($siteAdminDir);
		Fso::mkdir($siteAdminActionDir);
		$copyList = C('adminBaseCopyFile');
		foreach ($copyList as $filename) {
			copy($app_admin.$filename, $siteAdminDir.$filename);
		}
		
		// 全局配置
		$openedLangs = var_export($lang,true);
		$str = file_get_contents(APP_ROOT.'Data/siteCodeTemplate/global.cfg.txt');
		$replace = array(
			'{$db_host}'			=> $db_host,
			'{$db_name}'			=> $db_name,
			'{$db_user}'			=> $db_user,
			'{$db_pass}'			=> $db_pass,
			'{$db_charset}'			=> $db_charset,
			'{$app_charset}'		=> $app_charset,
			'{$lang}'				=> $default_lang,
			'{$default_timezone}'	=> $date_default_timezone,
			'{$server_domain}'		=> $domain,
			'{$tbl_pre}'			=> $tbl_pre,
			'{$adminThemeSign}'		=> 'Blue',
			'{$openedLangs}'		=> $openedLangs,
			'{$theme}'				=> $theme,
			'{$domain}'				=> $domain,
		);
		$str = strtr($str, $replace);
		$globalCfgFile = $siteDir.'App/Config/global.cfg.php';
		Fso::write($globalCfgFile, $str);
		
		// 管理员账号密码配置
		$privateKey = String::randStr(6);
		$admin_pass = md5(md5($admin_pass).md5($privateKey));
		$str = file_get_contents(APP_ROOT.'Data/siteCodeTemplate/adminpw.cfg.txt');
		$replace = array(
			'{$admin_name}'			=> $admin_name,
			'{$admin_password}'		=> $admin_pass,
			'{$admin_private_key}'	=> $privateKey,
		);
		$str = strtr($str, $replace);
		$adminpwCfgFile = $siteDir.'App/Config/adminpw.cfg.php';
		Fso::write($adminpwCfgFile, $str);
		
		if (empty($subject_tpl)) {
			$subject_tpl = "{:ToNickName:},你在{:websiteName:}网站上的留言有回复了 ";
		}
		if (empty($body_tpl)) {
			$body_tpl = "尊敬的{:ToNickName:}: \n{:reply:}";
		}
		$str = file_get_contents(APP_ROOT.'Data/siteCodeTemplate/email.cfg.txt');
		$replace = array(
			'{$smtp_ssl}'		=> $smtp_ssl,
			'{$smtp_host}'		=> $smtp_host,
			'{$smtp_port}'		=> $smtp_port,
			'{$smtp_fromname}'	=> $smtp_fromname,
			'{$smtp_email}'		=> $smtp_email,
			'{$smtp_user}'		=> $smtp_user,
			'{$smtp_pass}'		=> $smtp_pass,
			'{$subjectTpl}'		=> $subject_tpl,
			'{$bodyTpl}'		=> $body_tpl,
		);
		$str = strtr($str, $replace);
		$emailCfgFile = $siteDir.'App/Config/email.cfg.php';
		Fso::write($emailCfgFile, $str);
		
		// 站点基本配置
		$siteCfg = array(
			'siteName' => $name,
			'siteDomain' => $domain
		);
		$str = 'return '.var_export($siteCfg, true);
		$siteCfgFile = $siteDir.'App/Config/site.cfg.php';
		Fso::write($siteCfgFile, $str, 'php');
		
		// 复制基础类代码
		Fso::copyDir(APP_ROOT.'Base/', $siteDir.'App/Base/', '.svn');
		// 复制扩展类代码
		Fso::copyDir(APP_ROOT.'Util/', $siteDir.'App/Util/', '.svn');
		// 复制模块类代码
		$copyList = C('moBaseCopyFile');
		foreach ($copyList as $filename) {
			copy(APP_ROOT.'Mo/'.$filename, $siteDir.'App/Mo/'.$filename);
		}
		
		// 复制语言文件
		foreach ($lang as $l) {
			$ldir = APP_ROOT.'Lang/'.$l.'/';
			if (!is_dir($ldir)) {
				continue;
			}
			Fso::mkdir($siteDir.'App/Lang/'.$l);
			copy($ldir.'admin.lang.php', $siteDir.'App/Lang/'.$l.'/admin.lang.php');
			copy($ldir.'common.lang.php', $siteDir.'App/Lang/'.$l.'/common.lang.php');
		}
		
		
		// 复制前台显示模板
		$viewDir = $siteDir.'App/View/';
		$viewAdminDir = $viewDir.'Admin/Blue/';
		$viewSiteDir = $viewDir.'Site/'.$theme.'/';
		Fso::mkdir($viewAdminDir);
		Fso::mkdir($viewSiteDir);
		// 复制后台模板
		$copyList = C('adminViewBaseCopyFile');
		foreach ($copyList as $filename) {
			if ($filename == 'header.html.php') {
				$str = file_get_contents(APP_ROOT.'View/Admin/Blue/'.$filename);
				$replace = file_get_contents(APP_ROOT.'Data/siteCodeTemplate/adminHeader.html.txt');
				$str = preg_replace('~<!\-\-base_set\-\->[\S\s]+?<!\-\-//end base_set\-\->~', $replace, $str);
				Fso::write($viewAdminDir.$filename, $str);
				continue;
			}
			copy(APP_ROOT.'View/Admin/Blue/'.$filename, $viewAdminDir.$filename);
		}
		// 复制网站前台模板
		$copyList = C('siteViewBaseCopyFile');
		foreach ($copyList as $filename) {
			copy(APP_ROOT.'View/Site/'.$theme.'/'.$filename, $viewSiteDir.$filename);
		}
		
		global $web_root;
		// 复制前台程序代码
		Fso::mkdir($siteDir.'Webroot/res/Admin/Blue');
		Fso::mkdir($siteDir.'Webroot/res/attached');
		Fso::mkdir($siteDir.'Webroot/res/images');
		Fso::mkdir($siteDir.'Webroot/res/js');
		Fso::mkdir($siteDir.'Webroot/res/lib/kindeditor');
		Fso::mkdir($siteDir.'Webroot/res/themes/'.$theme);
		
		Fso::copyDir($web_root.'res/Admin/Blue/', $siteDir.'Webroot/res/Admin/Blue/', '.svn');
		Fso::copyDir($web_root.'res/js/', $siteDir.'Webroot/res/js/', '.svn');
		Fso::copyDir($web_root.'res/lib/kindeditor/', $siteDir.'Webroot/res/lib/kindeditor/', '.svn');
		Fso::copyDir($web_root.'res/themes/Blue/', $siteDir.'Webroot/res/themes/Blue/', '.svn');
	
		// 复制网站前台程序代码
		$copyList = C('siteBaseCopyFile');
		foreach ($copyList as $filename) {
			copy($web_root.$filename, $siteDir.'Webroot/'.$filename);
		}
		return true;
	}
	
	/**
	 * 添加站点
	 * @param array $data
	 */
	public static function add() 
	{
		extract($_POST);
		$now = time();
		
		$param = array($sign);
		$exist = Db::getOne($GLOBALS['tbl_pre'].self::TBL, 'sign=?', 'id', $param);
		if ($exist) {
			App::msg($GLOBALS['LSameNewsCategoryIsExist']);
			return false;
		}
		
		$cname = Db::getOne($GLOBALS['tbl_pre'].self::TBL_CATEGORY, 'id='.$cid, 'name');
		
		$lang = json_encode($lang);
		$module_list = json_encode($module_list);
		
		$data = array(
			'cid'			=> $cid,
			'cname'			=> $cname,
			'sign'			=> $sign,
			'name'			=> $name,
			'domain'		=> $domain,
			'theme'			=> $theme,
			'lang'			=> $lang,
			'default_lang'	=> $default_lang,
			'module_list'	=> $module_list,
			'note'			=> $note,
			'admin_name'	=> $admin_name,
			'admin_pass'	=> $admin_pass,
			'smtp_ssl'		=> $smtp_ssl,
			'smtp_host'		=> $smtp_host,
			'smtp_port'		=> $smtp_port,
			'smtp_fromname'	=> $smtp_fromname,
			'smtp_email'	=> $smtp_email,
			'smtp_user'		=> $smtp_user,
			'smtp_pass'		=> $smtp_pass,
			'subject_tpl'	=> $subject_tpl,
			'body_tpl'		=> $body_tpl,
			'db_host'		=> $db_host,
			'db_name'		=> $db_name,
			'db_user'		=> $db_user,
			'db_pass'		=> $db_pass,
			'db_charset'	=> $db_charset,
			'app_charset'	=> $app_charset,
			'date_default_timezone'	=> $date_default_timezone,
			'tbl_pre'		=> $tbl_pre,
			'create_time'	=> $now,
			'update_time'	=> $now,
		);
		$ret = Db::insert($GLOBALS['tbl_pre'].self::TBL, $data);
		
		if ($ret && $updatecode) {
			self::updateCode($_POST);
		}
		
		return $ret;
	}
	
	/**
	 * 修改站点
	 * @param array $data
	 */
	public static function modify() 
	{
		extract($_POST);
		$now = time();
		
		$cname = Db::getOne($GLOBALS['tbl_pre'].self::TBL_CATEGORY, 'id='.$cid, 'name');
		
		$lang = json_encode($lang);
		$module_list = json_encode($module_list);
		
		$data = array(
			'cid'			=> $cid,
			'cname'			=> $cname,
			'sign'			=> $sign,
			'name'			=> $name,
			'domain'		=> $domain,
			'theme'			=> $theme,
			'lang'			=> $lang,
			'default_lang'	=> $default_lang,
			'module_list'	=> $module_list,
			'note'			=> $note,
			'admin_name'	=> $admin_name,
			'admin_pass'	=> $admin_pass,
			'smtp_ssl'		=> $smtp_ssl,
			'smtp_host'		=> $smtp_host,
			'smtp_port'		=> $smtp_port,
			'smtp_fromname'	=> $smtp_fromname,
			'smtp_email'	=> $smtp_email,
			'smtp_user'		=> $smtp_user,
			'smtp_pass'		=> $smtp_pass,
			'subject_tpl'	=> $subject_tpl,
			'body_tpl'		=> $body_tpl,
			'db_host'		=> $db_host,
			'db_name'		=> $db_name,
			'db_user'		=> $db_user,
			'db_pass'		=> $db_pass,
			'db_charset'	=> $db_charset,
			'app_charset'	=> $app_charset,
			'date_default_timezone'	=> $date_default_timezone,
			'tbl_pre'		=> $tbl_pre,
			'create_time'	=> $now,
			'update_time'	=> $now,
		);
		$ret = Db::update($GLOBALS['tbl_pre'].self::TBL, $data, 'id='.$id);
		
		if ($ret && $updatecode) {
			self::updateCode($_POST);
		}
		
		return $ret;
	}
	
	/**
	 * 删除站点
	 * @param int $id
	 */
	public static function delete($id) 
	{
		$ret = Db::delete($GLOBALS['tbl_pre'].self::TBL, 'id='.(int)$id);
		return $ret;
	}
	
	/**
	 * 读取分类信息
	 * @param int $id
	 */
	public static function readCategory($id) 
	{
		return Db::read($GLOBALS['tbl_pre'].self::TBL_CATEGORY, (int)$id);
	}
	
	/**
	 * 添加站点分类
	 * @param string $name 分类名称
	 */
	public static function addCategory($name) 
	{
		$where = 'name=?';
		$param = array($name);
		$exist = Db::getOne($GLOBALS['tbl_pre'].self::TBL_CATEGORY, $where, 'id', $param);
		if ($exist) {
			App::msg($GLOBALS['LSameNewsCategoryIsExist']);
			return false;
		}
		$data = array(
			'name'	=> $name,
		);
		$ret = Db::insert($GLOBALS['tbl_pre'].self::TBL_CATEGORY, $data);
		return $ret;
	}
	
	/**
	 * 修改一条站点分类
	 * @param string $name 分类名称
	 */
	public static function modifyCategory($id, $name) 
	{
		$id = (int)$id;
		$where = 'id<>'.$id.' and name=?';
		$param = array($name);
		$exist = Db::getOne($GLOBALS['tbl_pre'].self::TBL_CATEGORY, $where, 'id', $param);
		if ($exist) {
			App::msg($GLOBALS['LSameNewsCategoryIsExist']);
			return false;
		}
		$where = 'name=?';
		$param = array($name);
		$exist = Db::getOne($GLOBALS['tbl_pre'].self::TBL_CATEGORY);
		$data = array(
			'name'	=> $name,
		);
		$ret = Db::update($GLOBALS['tbl_pre'].self::TBL_CATEGORY, $data, 'id='.$id);
		return $ret;
	}
	
	/**
	 * 删除一条站点分类
	 * @param int $id
	 */
	public static function deleteCategory($id) 
	{
		$exist = Db::getOne($GLOBALS['tbl_pre'].self::TBL, 'cid='.(int)$id, 'id');
		if ($exist) {
			App::msg($GLOBALS['LDeleteCategoryNeedNoSite']);
			return false;
		}
		$ret = Db::delete($GLOBALS['tbl_pre'].self::TBL_CATEGORY, 'id='.(int)$id);
		if (!$ret) {
			App::msg($GLOBALS['LFailure']);
		}
		return $ret;
	}
	
	/**
	 * 获取站点分类列表
	 * @param 
	 */
	public static function getCategoryList($hasPages=1)
	{
		$rows = Db::getCounts($GLOBALS['tbl_pre'].self::TBL_CATEGORY);
		if (!$rows && !is_null(Db::errors())) {
			App::msg(Db::$errors[2]);
			return false;
		}
		if ($hasPages)
		{
			Page::init(self::$pageSize, $rows);
			Page::setFromTo(self::$pageSize);
			$pageStart = Page::$from;
		} else {
			$hasPages = false;
			$pageStart = 0;
		}
		$list = Db::select(
	 					$GLOBALS['tbl_pre'].self::TBL_CATEGORY, 
	 					'', 
	 					'*', 
	 					null, 
	 					'', 
	 					$pageStart, 
	 					self::$pageSize
		);
		//如果列表有分页,则进行分页操作
		if ($hasPages == 1)
		{
			self::$pagePanel = Page::generate($_POST);
		}
		return $list;
	}
}













